#include "lv_port_indev.h"
#include "appdata/app_data.h"
#include "motor/motor.h"
#include "keyboard/keyboard.h"
#include "keyboard/Task_events.h"
lv_indev_t *indev_keypad;
lv_indev_t *indev_encoder;
lv_group_t *foc_group;
lv_group_t *kb_group;

bool old_encoder_is_pushed = 0;
void encoder_read(lv_indev_drv_t *indev_drv, lv_indev_data_t *data)
{

      static int now_num = 0;
      static int old_num = 0;
      if (dial_or_lvgl)
      {
            now_num = get_motor_position();
            data->enc_diff = 0;
            if (is_encoder_enabled())
            {
                  if (now_num - old_num > get_motor_position_width_radians())
                  {
                        data->enc_diff++;
                        SKY_running = 0;
                        old_num = get_motor_position();
                  }
                  else if (old_num - now_num > get_motor_position_width_radians())
                  {
                        data->enc_diff--;
                        SKY_running = 0;
                        old_num = get_motor_position();
                  }
            }
            data->state = encoder_is_pushed() ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
            old_encoder_is_pushed = encoder_is_pushed();
      }
}

void lv_port_indev_init(void)
{
      static lv_indev_drv_t indev_drv;
      lv_indev_drv_init(&indev_drv);
      indev_drv.type = LV_INDEV_TYPE_ENCODER;
      indev_drv.read_cb = encoder_read;
      indev_encoder = lv_indev_drv_register(&indev_drv);
      foc_group = lv_group_create();
      lv_group_set_default(foc_group);

      static lv_indev_drv_t indev_drv1;
      lv_indev_drv_init(&indev_drv1);
      indev_drv1.type = LV_INDEV_TYPE_KEYPAD;
      indev_drv1.read_cb = keypad_read;
      indev_keypad = lv_indev_drv_register(&indev_drv1);
      kb_group = lv_group_create();
}
uint8_t keynum = 0;
void keypad_read(lv_indev_drv_t *indev_drv, lv_indev_data_t *data)
{
      static uint32_t last_key = 0;
      if (keynum != 0)
      {
            data->state = LV_INDEV_STATE_PR;
            last_key = keynum + 32;
            keynum = 0;
      }
      else
            data->state = LV_INDEV_STATE_REL;
      data->key = last_key;
}
